package com.ebelter.scalebledemo;

import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.chipsea.healthscale.CsAlgoBuilderEx;
import com.ebelter.scaleblesdk.ScaleBleManager;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.ConnectCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.FirmwareUpgradeCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.callback.ScanResultCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IMeasureResultCallback;
import com.ebelter.scaleblesdk.ble.bluetooth.impl.IUserInfoChangedCallback;
import com.ebelter.scaleblesdk.model.BSDeviceType;
import com.ebelter.scaleblesdk.model.MeasureResult;
import com.ebelter.scaleblesdk.model.OfflineMeasureResult;
import com.ebelter.scaleblesdk.model.Scale;
import com.ebelter.scaleblesdk.model.ScaleUser;
import com.ebelter.scaleblesdk.model.Weight;
import com.ebelter.scaleblesdk.ble.upgrade.FirmwareUpgrader;
import com.ebelter.scaleblesdk.util.ULog;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tvSearchResult;
    private TextView tvBindStatus;
    private TextView tvReceiveData;
    private TextView tvOfflineData;
    private TextView tvFirmwareVersion;
    private TextView tvPercentFirmwareUpgrade;
    private ScaleBleManager sbm;
    private BluetoothDevice curDevice;
    private boolean isDeviceBound;
    private final static String TAG = "MainActivity";

    private static final String[] permissions = new String[]{
            Manifest.permission.BLUETOOTH,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH_ADMIN};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //初始化蓝牙模块
        ScaleBleManager.init(this);//初始化
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermissions();

        tvSearchResult = (TextView) findViewById(R.id.tv_search_result);
        tvBindStatus = (TextView) findViewById(R.id.tv_bind_status);
        tvReceiveData = (TextView) findViewById(R.id.tv_receive_data);
        tvOfflineData = (TextView) findViewById(R.id.tv_receive_offline_data);
        tvFirmwareVersion = (TextView) findViewById(R.id.tv_firmware_version);
        tvPercentFirmwareUpgrade = (TextView) findViewById(R.id.tv_percent_firmware_upgrade);

        findViewById(R.id.btn_bind).setOnClickListener(this);
        findViewById(R.id.btn_unbind).setOnClickListener(this);
        findViewById(R.id.btn_receive_offline).setOnClickListener(this);
        findViewById(R.id.btn_clear_user).setOnClickListener(this);
        findViewById(R.id.btn_firmware_version).setOnClickListener(this);
        findViewById(R.id.btn_ble_firmware_update).setOnClickListener(this);
        findViewById(R.id.btn_scale_firmware_update).setOnClickListener(this);

        findViewById(R.id.ceshibt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ULog.i(TAG,"-------------测试按钮按下----------");

                float height  = 174;
                float weight = 72.3f;
                int sex = 1;//0女1男
                int age=30;
                float resistance=422;
                //设置用户角色，1为运动员，0为普通用户
                int type=0;

                int orSex = sex;

                CsAlgoBuilderEx mBuilderEx = new CsAlgoBuilderEx();
                mBuilderEx.setUserInfo(height, weight, (byte) orSex, age, resistance);
                //设置用户角色，1为运动员，0为普通用户
                mBuilderEx.setMode(type);

                float BFR = mBuilderEx.getBFR();//脂肪率
                float VFR =mBuilderEx.getVFR();//内脂脂肪等级
                float TFR = mBuilderEx.getTFR();//水分率
                float MSW = mBuilderEx.getMSW();//骨盐量
                float BMR = mBuilderEx.getBMR();//基础代谢率
                float protein =mBuilderEx.getPM()/weight*100;//蛋白质
                float muscle =mBuilderEx.getSLM();//肌肉量
                float bodyAge =mBuilderEx.getBodyAge();//身体年龄
                float score =mBuilderEx.getScore();//身体得分
                float boneMuscle =mBuilderEx.getSMM();//骨骼肌

                String log="输入的 height = "+height+" weight = "+weight+" sex = "+sex+"  age ="+age+
                        "  阻抗resistance ="+resistance+" type="+type;


                String outLog="脂肪率BFR = "+BFR+"\n内脂脂肪等级VFR = "+VFR+"\n水分率TFR = "+TFR+"\n骨盐量MSW = "+MSW+
                        "\n基础代谢率BMR = "+BMR+"\n蛋白质protein="+protein+"\n肌肉量muscle = "+muscle+"\n身体年龄bodyAge="+bodyAge+
                        "\n身体得分bodyScore="+score+"\n骨骼肌boneMuscle ="+boneMuscle;

                ULog.i(TAG,log);//1
                ULog.i(TAG,outLog);


            }
        });




        initData();


        ScaleUser user = ScaleUser.getUser();
        String btId = user.toBtId("0000001");
        ULog.i(TAG, "----00001---btId = " + btId);

    }

    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String p:permissions){
                // 首先是判断
                if (ContextCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) {
                    ULog.i(TAG,"权限"+p+"没有授权成功1");
                    // Should we show an explanation?
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                        // 显示弹框给用户的解释 采用系统的
                        ULog.i(TAG,"权限"+p+"没有授权成功2--shouldShowRequestPermissionRationale");
                        ActivityCompat.requestPermissions(this, new String[]{p}, 1);
                    } else {
                        // No explanation needed, we can request the permission.
                        ActivityCompat.requestPermissions(this, new String[]{p}, 1);
                        ULog.i(TAG,"权限"+p+"没有授权成功3--requestPermissions--"+p);
                    }
                }else {
                    ULog.i(TAG,"权限"+p+"-----授权成功");
                }
            }
        }
    }

    private void initData() {

//        String btId = ScaleUser.getUser().toBtId("0000000001");
//        ULog.i(TAG, "-----zcq--btId = " + btId);


        sbm = ScaleBleManager.getInstance();
        sbm.setScanResultCallback(new ScanResultCallback() {

            @Override
            public void onDiscovered(final BluetoothDevice device) {
                curDevice = device;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvSearchResult.setText("搜索到设备：" + device.getName() + "\t" + device.getAddress());
                    }
                });

            }

        });
        sbm.startScan();


        //注册连接监听器
        sbm.registerConnectCallback(mConnectCallback);
        //注册秤用户信息改变监听器
        sbm.registerUserInfoChangedCallback(mUserInfoChangedCallback);
        //注册测量结果监听器
        sbm.registerMeasureResultCallback(measureResultCallback);
        //注册固件升级监听器
        sbm.registerFirmwareUpgradeCallback(mFirmwareUpdateCallback);

//        //是否已绑定体脂秤
//        isDeviceBound = sbm.isDeviceBound(this);
//        ULog.i(TAG, "-----initData--isDeviceBound = " + isDeviceBound);
//        if (!isDeviceBound) {
//            //  TODO 获取搜索设备结果，跳转到绑定设备界面，进行设备绑定
//
//        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_bind://绑定设备
                if (curDevice != null) {
                    sbm.startConnect(curDevice);
                }
                break;
            case R.id.btn_unbind://解绑
//                if (curDevice != null) {
//                    sbm.unbindDevice();
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            tvBindStatus.setText("当前绑定设备： ");
//                        }
//                    });
//                }
                break;
            case R.id.btn_receive_offline:
                //请求离线测量数据,连接成功下发用户信息后，才能请求离线测量数据，
                sbm.requestOfflineData(ScaleUser.getUser().getBtId());
                break;
            case R.id.btn_clear_user://清除用户信息
                sbm.sendDelAllUser();
                break;
            case R.id.btn_firmware_version://获取固件版本
                getFirmwareVersion();
                break;
            case R.id.btn_ble_firmware_update://蓝牙固件升级
                sbm.requestBleFirmwareUpgrade();
                break;
            case R.id.btn_scale_firmware_update://秤固件升级
                sbm.requestScaleFirmwareUpgrade();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        if (sbm != null) {
            sbm.releaseOnActivityDestroy();
        }
        super.onDestroy();
    }


    /**
     * 下发用户信息到秤
     */
    private void sendUserInfoToScale() {
        //初始化ScaleUser信息
        ScaleUser user = ScaleUser.getUser();

        user.setNike("张三");
        user.setUid(1);
        String btId = user.toBtId("00001");
        ULog.i(TAG, "-----sendUserInfoToScale--btId = " + btId);
        user.setBtId(btId);
        user.setAge(30);
        user.setSex(0);//0男1女
        user.setWeight(50.0f);
        user.setImpedance(500);
        user.setHeight(160);
        //设置角色，1为运动员，0为普通用户
        user.setRoleType(0);

        ULog.i(TAG, "-----sendUserInfoToScale----isLoginPattren = " + user.isLoginPattren());
        sbm.sendUserInfo(user);
    }

    /**
     * 获取固件版本
     */
    private void getFirmwareVersion() {

        //获取秤上的固件版本
        int scaleVersion = Scale.getInstance().getOtaVersion();
        int bleVersion = Scale.getInstance().getBleVersion();

        //获取本地秤固件文件的版本，用于显示的版本
        String firmwareVersion = FirmwareUpgrader.toFirmwareVersionShow(scaleVersion);
        ULog.i(TAG, "-----getFirmwareVersion------firmwareVersion = " + firmwareVersion);
        tvFirmwareVersion.setText("固件版本: " + firmwareVersion);

        //检查固件是否可升级
        boolean isScaleUpgradable = FirmwareUpgrader.isScaleUpgradable(scaleVersion);
        boolean isBleUpgradable = FirmwareUpgrader.isBleUpgradable(bleVersion);

        ULog.i(TAG, "-----getFirmwareVersion------isScaleUpgradable = " + isScaleUpgradable + ", isBleUpgradable = " + isBleUpgradable);
    }


    /**
     * 连接结果回调
     */
    private ConnectCallback mConnectCallback = new ConnectCallback() {


        @Override
        public void onConnected(final BluetoothDevice device, BSDeviceType bsDeviceType) {
            ULog.i(TAG, "------onDeviceConnected------连接成功！");
            curDevice = device;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvBindStatus.setText("当前绑定设备：" + device.getName());
                }
            });
            //发用户信息到秤
            sendUserInfoToScale();

        }

        @Override
        public void onScaleWake() {
            ULog.i(TAG, "------onScaleWake------");
        }

        @Override
        public void onScaleSleep() {
            ULog.i(TAG, "------onScaleSleep------");
        }

        @Override
        public void onDisConnected() {
            ULog.i(TAG, "------onDisConnected------");
        }


    };

    /**
     * 秤用户信息改变监听回调
     */
    private IUserInfoChangedCallback mUserInfoChangedCallback = new IUserInfoChangedCallback() {
        @Override
        public void onUserInfoUpdateSuccess() {
//            ULog.i(TAG, "-----onUserInfoUpdateSuccess--SDK里经常要更新秤用户信息，最好不要打印----");
        }

        @Override
        public void onDeleteAllUsersSuccess() {
            ULog.i(TAG, "-----onDeleteAllUsersSuccess------");
        }
    };

    /**
     * 测量结果监听回调
     */
    private IMeasureResultCallback measureResultCallback = new IMeasureResultCallback() {

        @Override
        public void onReceiveMeasureResult(final MeasureResult result) {
            ULog.i(TAG, "-----onFatMeasureResult------result = " + result);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addtext("接收到蓝牙信息：" + result);
                }
            });

        }

        @Override
        public void onWeightMeasureResult(final Weight weight) {
            ULog.i(TAG, "-----onWeightMeasureResult------weight = " + weight);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addtext("--onWeightMeasureResult--" + weight);
                }
            });
        }

        @Override
        public void onWeightOverLoad() {
            ULog.i(TAG, "-----onWeightOverLoad------");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addtext("接收到体重超重信息");
                }
            });
        }

        @Override
        public void onReceiveHistoryRecord(final OfflineMeasureResult result) {
            ULog.i(TAG, "-----onReceiveHistoryRecord------result = " + result);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addtext("接收到离线信息：" + result);
                }
            });
        }

        @Override
        public void onFatMeasureError(final int type) {
            ULog.i(TAG, "-----onFatMeasureError------type = " + type);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addtext("接收到错误信息 onFatMeasureError Error = " + type);
                }
            });
        }

        @Override
        public void onHistoryUploadDone() {
            ULog.i(TAG, "-----onHistoryUploadDone------");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addtext("历史数据接收完成");
                }
            });
        }

    };


    private void addtext(String log){
        if (tvReceiveData!=null){
            String s=tvReceiveData.getText().toString();
            if (s.length()>5000){
                s=s.substring(0,4999);
            }
            s=log+"\n"+s;
            tvReceiveData.setText(s);
        }
    }


    /**
     * 固件升级监听回调
     */
    private FirmwareUpgradeCallback mFirmwareUpdateCallback = new FirmwareUpgradeCallback() {

        @Override
        public void onUpgradeResponse(final int percent) {
            ULog.i(TAG, "-----onUpgradeResponse------percent = " + percent);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvPercentFirmwareUpgrade.setText("固件升级进度：" + percent + "%");
                }
            });
        }

        @Override
        public void onUpgradeResult(int result, int type) {
            ULog.i(TAG, "-----onUpgradeResult------result = " + result + ", type = " + type);
        }

        @Override
        public void onLowPower() {
            ULog.i(TAG, "-----onLowPower------");
        }

    };


}
